<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/30
 * Time: 14:36
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User;
use app\api\validate\NewAddress;
use app\api\service\Token as TokenService;
use app\lib\Exception\AddressException;
use app\lib\Exception\SuccessNotice;
use app\lib\Exception\UserException;

/*
 * 用户post地址信息
 * 用token获取uid
 * */


class Address extends BaseController
{
    protected $beforeActionList = [
        'checkBaseScope' => ['only' => 'newAddress, getAddress']
    ];

    public function getAddress(){
        //    token 获取uid
        $uid = TokenService::getCurrentUid();

        // uid 存在user表中 则合法
        $user = User::get($uid);
        if (!$user) {
            // 不合法的 uid
            throw new UserException();
        }

        if($user->address){
            return $user->address;
        }

        throw new AddressException();
    }

    public function newAddress()
    {
        $validate = new NewAddress();
        $validate->toCheck();

        //    token 获取uid
        $uid = TokenService::getCurrentUid();

        // uid 存在user表中 则合法
        $user = User::get($uid);
        if (!$user) {
            // 不合法的 uid
            throw new UserException();
        }

        //    获取地址信息
        $address = $validate->getDataByRule(input('post.'));

        //    保存地址

        if ($user->address) {
            //    更新地址
            $user->address->save($address);
        } else {
            //    创建地址
            $user->address()->save($address);
        }
        throw new SuccessNotice();
    }
}